<?php

class PayClaimForm extends CFormModel
{
	public $claim;
	public $claimId;
	public $place;
	public $site;
	
	public function rules()
	{
		return array(
			array('claimId, claim'),
		);
	}
	
	public function setClaimId($id)
	{
		$this->claimId = $id;
		$this->claim = Claim::model()->findByPk($id);
		$this->place = Place::model()->findByPk($this->claim->place_id);
	}
	
	public function payClaim()
	{
		return $this->placeToSite();
	}
	
	private function placeToSite()
	{
		$transaction = Yii::app()->db->beginTransaction();
		try {
			$this->site = new Site();
			$this->site->link = $this->claim->link;
			$this->site->place_id = $this->claim->place_id;
			$this->site->style = $this->site->logo = $this->site->gallery = $this->site->tab = 1;
			$this->place->owner_id = $this->claim->owner;
			
			if(!$this->site->save()){
				throw new Exception('Can not save site.');
			}
			if(!$this->place->save()){
				throw new Exception('Can not save place.');
			}
			if(!$this->claim->delete()){
				throw new Exception('Can not delete claim.');
			}
			$transaction->commit();
		} catch (Exception $e) {
			$transaction->rollback();
			echo $e->getMessage();
		}
	}
}